package light.mvc.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import light.mvc.model.wxn.AccessTokenBO;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;

public class BasisHttpRequest {
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String appid="wxad464dc223017a8d";
		String secret="81f26c50c043f11f28849c60396ea4d4";
		String url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret;
		//System.out.println(httpRequests(url));
	}
	
	private static Logger log = Logger.getLogger(AccessTokenBO.class);
    
   public JSONObject httpRequests(String requestUrl) {  
	       StringBuffer buffer = null;  
	       JSONObject resultJsonObject=null;
	 
	           // 建立连接  
	           URL url=null;
		try {
		    url = new URL(requestUrl);
		} catch (MalformedURLException e) {
		    // TODO Auto-generated catch block
		    SysLogger.error(BasisHttpRequest.class, "creat url error");
		    SysLogger.error(BasisHttpRequest.class, e.getMessage());
		    e.printStackTrace();
		}  
	           HttpURLConnection httpUrlConn=null;
		try {
		    httpUrlConn = (HttpURLConnection) url.openConnection();
		} catch (IOException e) {
		    SysLogger.error(BasisHttpRequest.class, "url connect error:"+url.getPath());
		    SysLogger.error(BasisHttpRequest.class, e.getMessage());
		    e.printStackTrace();
		}  
	           httpUrlConn.setDoInput(true);  
	           try {
		    httpUrlConn.setRequestMethod("GET");
		} catch (ProtocolException e) {
		    SysLogger.error(BasisHttpRequest.class, "set get method error");
		    SysLogger.error(BasisHttpRequest.class, e.getMessage());
		    e.printStackTrace();
		}  
	 
	           // 获取输入流  
	           InputStream inputStream=null;
		try {
		    inputStream = httpUrlConn.getInputStream();
		} catch (IOException e) {
		    SysLogger.error(BasisHttpRequest.class, "httpUrlConn get inputStream error");
		    SysLogger.error(BasisHttpRequest.class, e.getMessage());
		    e.printStackTrace();
		}  
	           InputStreamReader inputStreamReader=null;
		try {
		    inputStreamReader = new InputStreamReader(inputStream, "utf-8");
		} catch (UnsupportedEncodingException e) {
		    SysLogger.error(BasisHttpRequest.class, "new inputStreamReader error");
		    SysLogger.error(BasisHttpRequest.class, e.getMessage());
		    e.printStackTrace();
		}  
	           BufferedReader bufferedReader = new BufferedReader(inputStreamReader);  
	 
	           // 读取返回结果  
	           buffer = new StringBuffer();  
	           String str = null;  
	           try {
		    while ((str = bufferedReader.readLine()) != null) {  
		           buffer.append(str);  
		       }
		} catch (IOException e) {
		    SysLogger.error(BasisHttpRequest.class, "bufferedRead error");
		    SysLogger.error(BasisHttpRequest.class, e.getMessage());
		    e.printStackTrace();
		}  
	   resultJsonObject  = JSONObject.fromObject(buffer.toString());  
	           // 释放资源  
	   try {
		    bufferedReader.close();
		    inputStreamReader.close();  
		    inputStream.close();  
		} catch (IOException e) {
		    SysLogger.error(BasisHttpRequest.class, "close res error");
		    SysLogger.error(BasisHttpRequest.class, e.getMessage());
		    e.printStackTrace();
		}  
	           
	   		httpUrlConn.disconnect();  
	       return resultJsonObject;
	   } 
 
    public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
		JSONObject jsonObject = null;
		StringBuffer buffer = new StringBuffer();
		try {
			// 创建SSLContext对象，并使用我们指定的信任管理器初始化
			TrustManager[] tm = { new MyX509TrustManager() };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			// 从上述SSLContext对象中得到SSLSocketFactory对象
			SSLSocketFactory ssf = sslContext.getSocketFactory();

			URL url = new URL(requestUrl);
			HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
			httpUrlConn.setConnectTimeout(20000);  
			httpUrlConn.setReadTimeout(20000);  
			httpUrlConn.setSSLSocketFactory(ssf);

			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			// 设置请求方式（GET/POST）
			httpUrlConn.setRequestMethod(requestMethod);

			if ("GET".equalsIgnoreCase(requestMethod))
				httpUrlConn.connect();

			// 当有数据需要提交时
			if (null != outputStr) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				// 注意编码格式，防止中文乱码
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}

			// 将返回的输入流转换成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

			String str = null;
			while ((str = bufferedReader.readLine()) != null) {
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			// 释放资源
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();
			jsonObject = JSONObject.fromObject(buffer.toString());
		} catch (ConnectException ce) {
			log.error("Weixin server connection timed out.");
		} catch (Exception e) {
			e.printStackTrace();
			log.error("https request error:{}", e);
		}
		return jsonObject;
	}
}
